package com.link.play.fit.ai.ui.guide

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.aigestudio.wheelpicker.WheelPicker.OnWheelChangeListener
import com.link.play.fit.ai.GlobalConfig
import com.link.play.fit.ai.bean.LogWeightBean
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.databinding.FgHeightWeightBinding
import com.link.play.fit.ai.ui.guide.ac.GuidePbAc
import com.link.play.fit.ai.ui.setting.SetUserInfoAc
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlin.math.floor
import kotlin.math.roundToInt


class SettingHeightWeightFg : BasePageFragment<FgHeightWeightBinding>(FgHeightWeightBinding::inflate) {

    private val heightCm by lazy {
        val list = mutableListOf<String>()
        var start = 60 - 1
        repeat(243 - start) {
            start++
            list.add("$start cm")
        }
        list.toList()
    }
    private val heightFt by lazy {
        val list = mutableListOf<String>()
        var start = 1 - 1
        repeat(8 - start) {
            start++
            list.add("$start ft")
        }
        list.toList()
    }
    private val heightIn by lazy {
        val list = mutableListOf<String>()
        var start = 0 - 1
        repeat(11 - start) {
            start++
            list.add("$start in")
        }
        list.toList()
    }

    private val weightKg by lazy {
        val list = mutableListOf<String>()
        var start = 20 - 1
        repeat(360 - start) {
            start++
            list.add("$start kg")
        }
        list.toList()
    }
    private val weightLb by lazy {
        val list = mutableListOf<String>()
        var start = 40 - 1
        repeat(800 - start) {
            start++
            list.add("$start lb")
        }
        list.toList()
    }

    lateinit var userGuideState: MutableStateFlow<UserGuide>
    lateinit var logWeightBean: MutableStateFlow<LogWeightBean>
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.wheelHeightCm.data = heightCm
        binding.wheelFt.data = heightFt
        binding.wheelIn.data = heightIn

        binding.wheelWeightKg.data = weightKg
        binding.wheelWeightLb.data = weightLb

//        val userGuideState = (requireActivity() as GuidePbAc).viewModel.userGuideState

        when (val ac = requireActivity()) {
            is GuidePbAc -> {// 引导页面
                userGuideState = ac.viewModel.userGuideState
            }

            is SetUserInfoAc -> {//设置界面的要用
                userGuideState = ac.viewModel.userGuideState
                logWeightBean = ac.viewModel.logWeight
                binding.tvTitle.visibility = View.GONE
                binding.tvContent.visibility = View.GONE
            }

            else -> {
                userGuideState = (ac as GuidePbAc).viewModel.userGuideState
            }
        }
        lifecycleScope.launch {
            userGuideState.collectLatest {
                Log.e(TAG, "imperialMetric=${it.imperialMetric}")
                binding.switchCompat.isChecked=it.imperialMetric
                if (it.imperialMetric) {
                    binding.tvMetric.setTextColor(Color.parseColor("#FF1D1A23"))
                    binding.tvImperial.setTextColor(Color.parseColor("#FFDCDEDE"))

                    binding.flWheelHeightCm.visibility = View.VISIBLE
                    binding.flWheelWeightKg.visibility = View.VISIBLE

                    binding.llImperial.visibility = View.GONE
                    binding.flWheelWeightLb.visibility = View.GONE

                    val cmPosition = heightCm.indexOf("${it.heightCm} cm")
                    if (cmPosition != binding.wheelHeightCm.currentItemPosition) {
                        binding.wheelHeightCm.setSelectedItemPosition(cmPosition, false)
                    }

                    val kgPosition = weightKg.indexOf("${logWeightBean.value.weightKg} kg")
                    if (kgPosition != binding.wheelWeightKg.currentItemPosition) {
                        binding.wheelWeightKg.setSelectedItemPosition(kgPosition, false)
                    }
                } else {
                    binding.tvImperial.setTextColor(Color.parseColor("#FF1D1A23"))
                    binding.tvMetric.setTextColor(Color.parseColor("#FFDCDEDE"))

                    binding.llImperial.visibility = View.VISIBLE
                    binding.flWheelWeightLb.visibility = View.VISIBLE

                    binding.flWheelHeightCm.visibility = View.GONE
                    binding.flWheelWeightKg.visibility = View.GONE

                    val ftPosition = heightFt.indexOf("${it.heightFt} ft")
                    if (ftPosition != binding.wheelFt.currentItemPosition) {
                        binding.wheelFt.setSelectedItemPosition(ftPosition, false)
                    }
                    val inPosition = heightIn.indexOf("${it.heightIn} in")
                    if (inPosition != binding.wheelIn.currentItemPosition) {
                        binding.wheelIn.setSelectedItemPosition(inPosition, false)
                    }

                    val lbPosition = weightLb.indexOf("${logWeightBean.value.weightLbs} lb")
                    if (lbPosition != binding.wheelWeightLb.currentItemPosition) {
                        binding.wheelWeightLb.setSelectedItemPosition(lbPosition, false)
                    }

                }

            }
        }



        binding.switchCompat.setOnCheckedChangeListener { buttonView, isChecked ->
            userGuideState.update {
                if (isChecked) {//切换公制
                    val cm = covertFtInToCm(it.heightFt, it.heightIn)
                    it.heightCm = cm

                    val kg = convertLbsToKg(logWeightBean.value.weightLbs)
                    logWeightBean.value.weightKg = kg
                    GlobalConfig.imperialMetric=true
                } else {//切换英制
                    val ftIn = convertCmToFtIn(it.heightCm.toDouble())
                    it.heightFt = ftIn.first
                    it.heightIn = ftIn.second

                    val lb = convertKgToLbs(logWeightBean.value.weightKg)
                    logWeightBean.value.weightLbs = lb
                    GlobalConfig.imperialMetric=false
                }
                it.copy(imperialMetric = isChecked)
            }
        }

        binding.wheelHeightCm.setOnWheelChangeListener(object : OnWheelChangeListener {
            override fun onWheelScrolled(offset: Int) = Unit
            override fun onWheelScrollStateChanged(state: Int) = Unit
            override fun onWheelSelected(position: Int) {
                runCatching {
                    val newCm = heightCm[position].split(" ")[0].toInt()
                    userGuideState.value.heightCm = newCm
                }
            }
        })

        binding.wheelFt.setOnWheelChangeListener(object : OnWheelChangeListener {
            override fun onWheelScrolled(offset: Int) = Unit
            override fun onWheelScrollStateChanged(state: Int) = Unit
            override fun onWheelSelected(position: Int) {
                runCatching {
                    val newFt = heightFt[position].split(" ")[0].toInt()
                    userGuideState.value?.heightFt = newFt
                }
            }

        })
        binding.wheelIn.setOnWheelChangeListener(object : OnWheelChangeListener {
            override fun onWheelScrolled(offset: Int) = Unit
            override fun onWheelScrollStateChanged(state: Int) = Unit
            override fun onWheelSelected(position: Int) {
                runCatching {
                    val newIn = heightIn[position].split(" ")[0].toInt()
                    userGuideState.value.heightIn = newIn
                }
            }

        })
        binding.wheelWeightKg.setOnWheelChangeListener(object : OnWheelChangeListener {
            override fun onWheelScrolled(offset: Int) = Unit
            override fun onWheelScrollStateChanged(state: Int) = Unit
            override fun onWheelSelected(position: Int) {
                runCatching {
                    val newKg = weightKg[position].split(" ")[0].toInt()
                    logWeightBean.value.weightKg = newKg
//                    if (userGuideState.value.goal == 0) {
//                        userGuideState.value.goalWeightKg = newKg + 10
//                    }
//                    if (userGuideState.value.goal == 1) {
//                        userGuideState.value.goalWeightKg = newKg - 10
//                    }
                }
            }

        })
        binding.wheelWeightLb.setOnWheelChangeListener(object : OnWheelChangeListener {
            override fun onWheelScrolled(offset: Int) = Unit
            override fun onWheelScrollStateChanged(state: Int) = Unit
            override fun onWheelSelected(position: Int) {
                runCatching {
                    val newLbs = weightLb[position].split(" ")[0].toInt()
                    logWeightBean.value.weightLbs = newLbs
//                    if (userGuideState.value.goal == 0) {
//                        userGuideState.value.goalWeightLbs = newLbs + 10
//                    }
//                    if (userGuideState.value.goal == 1) {
//                        userGuideState.value.goalWeightLbs = newLbs - 10
//                    }
                }
            }
        })
    }


    private fun convertCmToFtIn(cm: Double): Pair<Int, Int> {
        // 1 英尺 = 30.48 厘米
        val feet = floor(cm / 30.48).toInt()
        // 剩余的厘米转换为英寸，1 英寸 = 2.54 厘米
        val inches = ((cm - feet * 30.48) / 2.54).roundToInt() // 四舍五入到最接近的整数
        return Pair(feet, inches)
    }

    private fun covertFtInToCm(feet: Int, inches: Int): Int {
        // 1 英尺 = 30.48 厘米
        val feetToCm = feet * 30.48
        // 1 英寸 = 2.54 厘米
        val inchesToCm = inches * 2.54
        // 总厘米数
        val totalCm = feetToCm + inchesToCm
        // 返回结果，四舍五入到最接近的整数
        return totalCm.roundToInt()
    }

    private fun convertKgToLbs(kg: Int): Int {
        // 1 kg = 2.20462 lb，四舍五入为 2.205
        val lb = kg * 2.205
        // 返回结果，四舍五入到最接近的整数
        return lb.roundToInt()
    }

    private fun convertLbsToKg(lb: Int): Int {
        // 1 lb = 0.453592 kg，四舍五入为 0.454
        val kg = lb * 0.454
        // 返回结果，四舍五入到最接近的整数
        return kg.roundToInt()
    }
}